package com.ivan.stu.notetool.activity;

import android.Manifest;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.ComponentName;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.Rect;
import android.graphics.Typeface;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.support.annotation.RequiresApi;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.text.Editable;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.TextWatcher;
import android.text.style.ImageSpan;
import android.text.style.StyleSpan;
import android.text.style.UnderlineSpan;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.blankj.utilcode.util.ScreenUtils;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.resource.bitmap.RoundedCorners;
import com.bumptech.glide.request.RequestOptions;
import com.bumptech.glide.request.target.SimpleTarget;
import com.bumptech.glide.request.transition.Transition;
import com.google.gson.Gson;
import com.ivan.stu.notetool.ImageEdit.IMGEditActivity;
import com.ivan.stu.notetool.R;
import com.ivan.stu.notetool.View.LoadDialog;
import com.ivan.stu.notetool.View.Loading_view;
import com.ivan.stu.notetool.adapter.NoteSubjectAdapter;
import com.ivan.stu.notetool.callback.NegativeCallBack;
import com.ivan.stu.notetool.callback.PositiveCallBack;
import com.ivan.stu.notetool.model.MySubjectBean;
import com.ivan.stu.notetool.model.NoteBean;
import com.ivan.stu.notetool.model.NotifyFinishEvent;
import com.ivan.stu.notetool.model.NotifyToRefreshNoteEvent;
import com.ivan.stu.notetool.network.api.SafeApiManager;
import com.ivan.stu.notetool.network.intercepter.NetworkTransformer;
import com.ivan.stu.notetool.network.postbody.GetNoteSubjectPostBody;
import com.ivan.stu.notetool.network.postbody.NoteIDPostBody;
import com.ivan.stu.notetool.network.postbody.NotePostBody;
import com.ivan.stu.notetool.network.response.ApiResponse;
import com.ivan.stu.notetool.network.response.MySubjectResponse;
import com.ivan.stu.notetool.network.response.NoteIDResponse;
import com.ivan.stu.notetool.network.response.NoteResponse;
import com.ivan.stu.notetool.network.response.OperateNoteResponse;
import com.ivan.stu.notetool.network.response.Response;
import com.ivan.stu.notetool.utils.ActivityCollectorUtils;
import com.ivan.stu.notetool.utils.ConstrantManager;
import com.ivan.stu.notetool.utils.DateUtils;
import com.ivan.stu.notetool.utils.DeviceUtils;
import com.ivan.stu.notetool.utils.EditTextUtil;
import com.ivan.stu.notetool.utils.FileManager;
import com.ivan.stu.notetool.utils.Global;
import com.ivan.stu.notetool.utils.ImageUtil;
import com.ivan.stu.notetool.utils.ImageUtils;
import com.ivan.stu.notetool.utils.LookPicture;
import com.ivan.stu.notetool.utils.NetworkUtil;
import com.ivan.stu.notetool.utils.OkHttpUtils;
import com.ivan.stu.notetool.utils.PermissionsManager;
import com.ivan.stu.notetool.utils.PermissionsResultAction;
import com.ivan.stu.notetool.utils.ScreenUtil;
import com.ivan.stu.notetool.utils.SoftInputUtil;
import com.ivan.stu.notetool.utils.TextViewUtils;


import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.File;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import io.reactivex.observers.ResourceObserver;
import okhttp3.OkHttpClient;


import static com.blankj.utilcode.util.ScreenUtils.getScreenHeight;
import static com.blankj.utilcode.util.ScreenUtils.getScreenWidth;

public class EditNoteActivity extends AppCompatActivity implements View.OnClickListener{

    private String mCurrentSysID = "";
    private String mCurrentSysName = "";
    private String mNoteContent = "";
    private String mNoteTitle = "";
    private ImageView iv_left_back;
    private TextView tv_save_note,tv_photo;
    private EditText et_titile,et_content;
    private Handler mHandler = new Handler();
    private NoteBean bean;
    private String url = "http://192.168.3.158:1314/api/V2/NoteTool/UploadImg";
    private boolean isFromSearch = false;
    private RelativeLayout rl_titile;
    private LinearLayout ll_content;
    private Loading_view view ;
    private String path = Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator + "mms";
    private File photo_file = new File(path);
    private String photoPath;
    private int screenWidth;
    private List<String> mImageList = new ArrayList<>();
    private List<Integer> mErrorList = new ArrayList<>();
    private List<Integer> mImageIndexs = new ArrayList<>();
    private HashMap<Integer,ImageSpan> mDefaultSpans = new HashMap<>();
    private HashMap<Integer,ImageSpan> mErrorSpans = new HashMap<>();
    private  SpannableString spannable;
    private OkHttpClient client;
    private String input;
    private List<String> underlineList = new ArrayList<>();
    private List<String> strongList = new ArrayList<>();
    private List<String> underlineDouble = new ArrayList<>();
    private List<String> strongDouble  = new ArrayList<>();
    private List<String> doubleStyle = new ArrayList<>();
    private File currentFile = null;
    private File imageEditedFile = null;
    private boolean mIsSoftKeyBoardShowing = false;
    private RadioGroup radioGroup;
    private PopupWindow mSoftKeyboardTopPopupWindow;
    private LinearLayout mContainer;
    private ImageView iv_highlight_star;
    private boolean isMatter;
    private ImageView iv_subject_right;
    private List<MySubjectBean> subjectList = new ArrayList<>();
    private NoteSubjectAdapter noteSubjectAdapter;
    private PopupWindow popClass;
    private TextView tv_choose_subject;
    private ListView listview;
    private boolean isExpendClass;
    private int mFirstSubLocation = 0;
    private String subjectName = "";
    private String subjectId = "";
    private int IsKeyPoint = 0;
    private TextView tv_source;
    private LoadDialog mLoadDialog;
    private boolean isSummit = false;
    private boolean isSave = false;
    private boolean isTitleChange;
    private boolean isContentChange;
    private boolean isSubjectChange;
    private boolean isKeyChange;
    private long firstTime;
    private String systemId = "";
    private String systemName = "";
    private NoteBean NoteDetailbean;

    private boolean isShowKeyBoard = false;


    @RequiresApi(api = Build.VERSION_CODES.N)
    @Override
    protected void onCreate(Bundle savedInstanceState) {

        setDesignStyle(this);
        super.onCreate(savedInstanceState);
        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
        setContentView(R.layout.activity_edit_note);
        WindowManager wm = (WindowManager) this
                .getSystemService(Context.WINDOW_SERVICE);
        screenWidth = wm.getDefaultDisplay().getWidth();

        ActivityCollectorUtils.addActivity(EditNoteActivity.this,EditNoteActivity.class);


     //   ActivityCollectorUtils.addActivity(this);


        initIntent();
    //    initSystemID();
        findViews();
        initImageList();
        getNoteByID();


        //系统集成中没有学科筛选的功能。

    //    getNoteSubjectList();

        if (!EventBus.getDefault().isRegistered(this)) {

            EventBus.getDefault().register(this);

        }

    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void notifyFinish(NotifyFinishEvent event){

        if (event.getFinishSigin() == 1){

            mNoteContent = et_content.getText().toString();
            mNoteTitle = et_titile.getText().toString();

            if (mNoteTitle.equals("")){

                mNoteTitle = DateUtils.getNowDate();
            }

            String result = EditTextUtil.convertSpannedToRichText(et_content.getText());
            mNoteContent = result;

            editNote(false);
            finish();
        }

    }

    public void initIntent(){

        Intent intent = getIntent();
        bean =  (NoteBean) intent.getSerializableExtra("NoteBean");

        //这里还要获跳转链接进行查看笔记来源的功能
        isFromSearch = intent.getBooleanExtra("IsFromSearch",false);
        input = bean.getNoteContent().replaceAll("<br/>","\n");

        input = input.replaceAll("<p.*?>","\n");  //去除<p>标签
        input = input.replaceAll("</p>","\n");    //去除</p>标签
        input = input.replaceAll("&nbsp;"," ");   //去除&nbsp符号
        handleDoubleStyle();   //记录双属性标签的位置
        handleStyleSpan();    //记录下划线标签和字体加粗标签所覆盖的内容
        input = input.replaceAll("<span.*?>","");
        input = input.replaceAll("</span.*?>","");
        input = input.replaceAll("<strong.*?>","");   //去除strong标签后再次编辑可能会有回显的问题
        input = input.replaceAll("</strong.*?>","");
   //     Log.e("去除格式的input",input);

        subjectId = bean.getSubjectID();
        subjectName = bean.getSubjectName();

        systemId= bean.getSubjectID();
        systemName = bean.getSystemName();

        //input去除格式标签后的笔记内容字符串
    }
    private void setDesignStyle(Activity activity) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            Window window = activity.getWindow();
            ViewGroup decorView = (ViewGroup) window.getDecorView();
            int option = View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_STABLE;
            decorView.setSystemUiVisibility(option);
            window.setStatusBarColor(Color.TRANSPARENT);
        } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            Window window = activity.getWindow();
            window.addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
        }
    }


    private void handleDoubleStyle() {

        String reg4 = "<span[^>]*>([^<]*)</span>";
        String reg3 = "<strong[^>]*>([^<]*)</strong>";

          String reg = "<span.*?>.+?</span>";
          String reg1 = "<strong.*?>.+?</strong>";

        Pattern p = Pattern.compile(reg);

        Matcher m = p.matcher(input);

        while (m.find()){

            String spanStr = m.group();

            if (spanStr.contains("</strong>")){

                underlineDouble.add(m.group());
       //         Log.e("underlineDouble",m.group());

                Pattern p_under_strong = Pattern.compile(reg3);
                Matcher m_under_strong = p_under_strong.matcher(m.group());
                while (m_under_strong.find()){

          //          Log.e("m_under_strong",m_under_strong.group(1));
                    doubleStyle.add(m_under_strong.group(1));
                }
            }
        }

        Pattern p1 = Pattern.compile(reg1);
        Matcher m1 = p1.matcher(input);

        while (m1.find()){

            if (m1.group().contains("underline")&&m1.group().contains("</span>")){

                strongDouble.add(m1.group());

         //       Log.e("strongDouble",m1.group());

                Pattern p_strong_under = Pattern.compile(reg4);
                Matcher m_strong_under = p_strong_under.matcher(m1.group());

                while (m_strong_under.find()){

          //          Log.e("m_strong_under",m_strong_under.group(1));
                    doubleStyle.add(m_strong_under.group(1));

                }
            }
        }
    }

    @RequiresApi(api = Build.VERSION_CODES.N)
    private void findViews() {

        mLoadDialog = new LoadDialog.Builder(EditNoteActivity.this).setMsg("正在上传..").setCancelable(false).build();

        ll_content = findViewById(R.id.ll_content);
        iv_left_back =  findViewById(R.id.iv_left_back);
        tv_save_note =  findViewById(R.id.tv_complete);
        et_content = findViewById(R.id.ed_note_content);
        et_titile = findViewById(R.id.ed_note_title);
        tv_photo = findViewById(R.id.tv_photo);
        iv_subject_right = findViewById(R.id.iv_subject_right);
        iv_subject_right.setVisibility(View.INVISIBLE);
        tv_choose_subject = findViewById(R.id.tv_choose_subject);
        mContainer = findViewById(R.id.ll_container);
        iv_highlight_star = findViewById(R.id.iv_highlight_star);
        tv_source = findViewById(R.id.tv_source);

        tv_photo.setVisibility(View.INVISIBLE);
        iv_left_back.setOnClickListener(this);
        tv_save_note.setOnClickListener(this);
        ll_content.setOnClickListener(this);
        iv_highlight_star.setOnClickListener(this);
    //    tv_choose_subject.setOnClickListener(this);  //系统集成没有学科筛选
        tv_source.setOnClickListener(this);
        tv_choose_subject.setText(bean.getSubjectName());

        if (bean.getMaterialIndex() == -1){//展示来源是来自某份资料


            if (bean.getResourceName()!=null && bean.getResourceName().length()>20){

                tv_source.setText(bean.getResourceName().substring(0,17)+"...");
            }else {

                tv_source.setText(bean.getResourceName());
            }



        }else {  //展示来源是第几大题

            tv_source.setText(bean.getMaterialID());  //针对课后作业

        }

        EditTextUtil.setEditTextInputSpace(EditNoteActivity.this,et_titile,0);
        EditTextUtil.setEditTextInputSpace(EditNoteActivity.this,et_content,1);

        et_content.setOnClickListener(this);
        et_titile.setOnClickListener(this);

        et_content.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

                if (isShowKeyBoard){

                    //            Log.e("输入字符",charSequence.toString().trim()+"");

                    //         if (!charSequence.toString().trim().equals("")){

                    isContentChange = true;

                    //                Log.e("isTitleChange",isTitleChange+"");
                    //             }
                }

            }

            @Override
            public void afterTextChanged(Editable editable) {



            }
        });

        et_titile.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

                if (isShowKeyBoard){

                    //            Log.e("输入字符",charSequence.toString().trim()+"");

                    //         if (!charSequence.toString().trim().equals("")){

                    isTitleChange = true;

                    //                Log.e("isTitleChange",isTitleChange+"");
                    //             }
                }

            }

            @Override
            public void afterTextChanged(Editable editable) {



            }
        });

        et_content.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {

                Rect rect = new Rect();
                // 获取当前页面窗口的显示范围
                getWindow().getDecorView().getWindowVisibleDisplayFrame(rect);
                int screenHeight = getScreenHeight();
                int keyboardHeight = screenHeight - rect.bottom; // 输入法的高度
                boolean preShowing = mIsSoftKeyBoardShowing;
                if (Math.abs(keyboardHeight) > screenHeight / 5) {

                    mIsSoftKeyBoardShowing = true; // 超过屏幕五分之一则表示弹出了输入法
                    showKeyboardTopPopupWindow(getScreenWidth() / 2, keyboardHeight);

                }else {

                    if (preShowing) {
                        closePopupWindow();
                    }

                    mIsSoftKeyBoardShowing = false;
                }

            }
        });

        initStyle();
        
        if (bean!=null){

            if (bean.getIsKeyPoint() == 1){

                IsKeyPoint = 1;
                iv_highlight_star.setBackgroundResource(R.mipmap.notetool_highlight_star);
            }else {

                IsKeyPoint = 0;
                iv_highlight_star.setBackgroundResource(R.mipmap.notetool_highlight_star_unselet);
            }
        }
    }


    public void initStyle(){

        if (bean!=null){

            showDefaultContent(new AsyncCallback() {
                @Override
                public void onCompleted(Spannable spannable) {

             //       et_content.setText(spannable);

                }

                @Override
                public void onFinish() {  //当所有默认图片都设置好了之后开始加载图片 ，主线程回调

                    et_content.setText(spannable);  //显示视图

                    showUnderline(new AsyncCallback() {
                        @Override
                        public void onCompleted(Spannable spannable) {
                            et_content.setText(spannable);
                        }

                        @Override
                        public void onFinish() {

                        }
                    });  //显示下划线

                    showStrong(new AsyncCallback() {
                        @Override
                        public void onCompleted(Spannable spannable) {
                            et_content.setText(spannable);
                        }

                        @Override
                        public void onFinish() {

                        }
                    });     //显示字体加粗

                    showDoubleStyle(new AsyncCallback() {
                        @Override
                        public void onCompleted(Spannable spannable) {

                            et_content.setText(spannable);

                        }
                        @Override
                        public void onFinish() {

                        }
                    });  //显示双属性（下划线和字体加粗）

                    showPictures();  //显示真实的图片

                }
            });   //过滤和预处理一些特殊标签。


            et_titile.setText(bean.getNoteTitle());

        }
    }

    public interface AsyncCallback{

        void onCompleted(Spannable spannable);

        void onFinish();
    }

    private void closePopupWindow() {
        if (mSoftKeyboardTopPopupWindow != null && mSoftKeyboardTopPopupWindow.isShowing()) {
            mSoftKeyboardTopPopupWindow.dismiss();
            mSoftKeyboardTopPopupWindow = null;
        }
    }


    private void showKeyboardTopPopupWindow(int x, int y) {

        isShowKeyBoard = true;
        if (mSoftKeyboardTopPopupWindow != null && mSoftKeyboardTopPopupWindow.isShowing()) {
            updateKeyboardTopPopupWindow(x, y); //可能是输入法切换了输入模式，高度会变化（比如切换为语音输入）
            return;
        }

        View popupView = getLayoutInflater().inflate(R.layout.soft_keyboard_top_tool_view, null);

        popupView.findViewById(R.id.tv_clear).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                if (!et_content.getText().toString().trim().equals("")){

                    TextViewUtils.showDialog(EditNoteActivity.this, "您确定要清空所有笔记内容吗？", new PositiveCallBack() {
                        @Override
                        public void positiveCallBack(AlertDialog dialog) {

                            if (dialog!=null){

                                dialog.dismiss();
                            }

                            et_content.setText("");

                        }
                    }, new NegativeCallBack() {
                        @Override
                        public void negativeCallBack(AlertDialog dialog) {

                            //     et_content.setText("");
                            if (dialog!=null){

                                dialog.dismiss();

                            }
                        }
                    });

                }
            }
        });


        radioGroup = popupView.findViewById(R.id.radioGroup);

        if (ConstrantManager.currentSystemid.equals("b30") || ConstrantManager.currentSystemid.equals("B30")){

            radioGroup.findViewById(R.id.rb_camera).setVisibility(View.GONE);

        }else {
            radioGroup.findViewById(R.id.rb_camera).setVisibility(View.VISIBLE);

        }


 /*       LinearLayout.LayoutParams params;

        if (ScreenUtil.getScreenWidth(EditNoteActivity.this)>720){

            params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,60);
        }else {

            params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,50);
        }

        params.gravity = Gravity.CENTER_VERTICAL;

        radioGroup.setLayoutParams(params);*/

        radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup radioGroup, int i) {


                RadioButton radioButton = radioGroup.findViewById(i);

                int id = radioButton.getId();
                if (id == R.id.rb_camera){

                    verifyPermissions(EditNoteActivity.this,100);

                }else if (id == R.id.rb_picture){

                    verifyPermissions(EditNoteActivity.this,200);

                }else {

                    verifyPermissions(EditNoteActivity.this,300);

                }
            }
        });


        mSoftKeyboardTopPopupWindow = new PopupWindow(popupView, ViewGroup.LayoutParams.MATCH_PARENT, 80, true);
        mSoftKeyboardTopPopupWindow.setTouchable(true);
        mSoftKeyboardTopPopupWindow.setOutsideTouchable(false);
        mSoftKeyboardTopPopupWindow.setFocusable(false);
        mSoftKeyboardTopPopupWindow.setInputMethodMode(PopupWindow.INPUT_METHOD_NEEDED); //解决遮盖输入法
        mSoftKeyboardTopPopupWindow.showAtLocation(mContainer, Gravity.BOTTOM, x, y);
    }

    private void updateKeyboardTopPopupWindow(int x, int y) {
        if (mSoftKeyboardTopPopupWindow != null && mSoftKeyboardTopPopupWindow.isShowing()) {
            mSoftKeyboardTopPopupWindow.update(x, y, mSoftKeyboardTopPopupWindow.getWidth(), mSoftKeyboardTopPopupWindow.getHeight());
        }
    }

    public void openCamera( ) {
        //獲取系統版本
        int currentapiVersion = Build.VERSION.SDK_INT;

  //      Log.e("当前系统版本",currentapiVersion+"");
        // 激活相机
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        // 判断存储卡是否可以用，可用进行存储
        if (hasSdcard()) {
            if (!photo_file.exists()) {

                photo_file.mkdirs();
            }

            try {

                String temp = DateUtils.dateToStamp(DateUtils.getNowDate());
                photo_file = new File(path, "/"+temp+".jpg");

                if (photo_file != null) {

                    Uri imageUri;


                    if (currentapiVersion < 24) {

                        Log.e("走的这","小于7.0");
                        // 从文件中创建uri
                        imageUri = Uri.fromFile(photo_file);
                        intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
                    } else {

                        Log.e("走的这","大于7.0");
                        //兼容android7.0 使用共享文件的形式
                        ContentValues contentValues = new ContentValues(1);
                        contentValues.put(MediaStore.Images.Media.DATA, photo_file.getAbsolutePath());
                        //检查是否有存储权限，以免崩溃
                        if (ContextCompat.checkSelfPermission(EditNoteActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE)
                                != PackageManager.PERMISSION_GRANTED) {
                            //申请WRITE_EXTERNAL_STORAGE权限
                            Toast.makeText(EditNoteActivity.this,"请开启存储权限",Toast.LENGTH_SHORT).show();
                            return ;
                        }
                        imageUri = getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, contentValues);
                        intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);

                    }
                    // 开启一个带有返回值的Activity，请求码为PHOTO_REQUEST_CAREMA
                    if (ContextCompat.checkSelfPermission(EditNoteActivity.this, Manifest.permission.CAMERA)
                            != PackageManager.PERMISSION_GRANTED){

                        ActivityCompat.requestPermissions(EditNoteActivity.this, new String[]{
                                Manifest.permission.CAMERA}, 400);

                    }else {

                        startActivityForResult(intent, 1);
                    }


                }


            } catch (ParseException e) {
                e.printStackTrace();
            }
        }else {

            Log.e("aaaaaaaaaaa","没有sd卡");
        }
    }

    public void verifyPermissions(Activity activity,int requestCode) {

        if (ActivityCompat.checkSelfPermission(activity, Manifest.permission.WRITE_EXTERNAL_STORAGE)
                != PackageManager.PERMISSION_GRANTED
                || ActivityCompat.checkSelfPermission(activity, Manifest.permission.READ_EXTERNAL_STORAGE)
                != PackageManager.PERMISSION_GRANTED
                ) {
            //     Toast.makeText(this, "没有获取权限,请手动开启权限", Toast.LENGTH_SHORT).show();

            // 申请一个（或多个）权限，并提供用于回调返回的获取码（用户定义）
            ActivityCompat.requestPermissions(activity, new String[]{
                     Manifest.permission.READ_EXTERNAL_STORAGE,Manifest.permission.WRITE_EXTERNAL_STORAGE}, requestCode);
        } else {  //已授权

            if (requestCode == 100){

                openCamera();


            }else if (requestCode == 200){
                openAblum();

            }else if (requestCode == 300){

                openPanel();
            }else {


            }

       //     openCamera();

        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        switch (requestCode) {
            case 100:

            //    Toast.makeText(this, "code"+grantResults[0], Toast.LENGTH_SHORT).show();

                if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {

                    Log.e("aaaaaaaaaaaa","授权成功！！！！");

                    openCamera();

                } else {
                    // 没有获取到权限，做特殊处理

                    Toast.makeText(this, "没有获取权限,请手动开启权限", Toast.LENGTH_SHORT).show();

                }
                break;
            case 200:

          //      Toast.makeText(this, "code"+grantResults[0], Toast.LENGTH_SHORT).show();

                if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {

                    Log.e("aaaaaaaaaaaa","授权成功！！！！");

                    openAblum();

                } else {
                    // 没有获取到权限，做特殊处理

                    Toast.makeText(this, "没有获取权限,请手动开启权限", Toast.LENGTH_SHORT).show();

                }


                break;
            case 300:

           //     Toast.makeText(this, "code"+grantResults[0], Toast.LENGTH_SHORT).show();

                if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {

                    Log.e("aaaaaaaaaaaa","授权成功！！！！");

                    openPanel();

                } else {
                    // 没有获取到权限，做特殊处理

                    Toast.makeText(this, "没有获取权限,请手动开启权限", Toast.LENGTH_SHORT).show();

                }

                break;
            case 400:

                if (grantResults[0] == PackageManager.PERMISSION_GRANTED){

                    Log.e("aaaaaaaaaaa","开启相机权限已开启！");

                    openCamera();

                }else {

                    Log.e("aaaaaaaaaaa","开启相机权限被拒！");

                    Toast.makeText(this, "没有获取权限,请手动开启相机权限", Toast.LENGTH_SHORT).show();

                }

                break;
        }
    }

    private void openPanel() {

        try {

            String temp = DateUtils.dateToStamp(DateUtils.getNowDate());

            FileManager.init(EditNoteActivity.this,ConstrantManager.FILE_MANAGER_ROOT);
            imageEditedFile = FileManager.getFile(FileManager.getRootDir(),temp+".jpg");
            IMGEditActivity.openEditor(EditNoteActivity.this,null,imageEditedFile.getAbsolutePath());  //打开手写画板

        } catch (ParseException e) {
            e.printStackTrace();
        }


    }

    private void openAblum() {

        Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
        startActivityForResult(intent, 0);

    }

    public static boolean hasSdcard() {
        return Environment.getExternalStorageState().equals(
                Environment.MEDIA_MOUNTED);
    }

    //设置字体加粗和下划线双属性

    private void showDoubleStyle(final AsyncCallback callback) {
    //    Log.e("doubleStyle",doubleStyle.size()+"");

        if (doubleStyle!=null&&doubleStyle.size()>0){

            for (int i = 0;i<doubleStyle.size();i++){

                //在笔记内容中匹配带有双标签的内容，并设置双样式
                Pattern p_double = Pattern.compile(doubleStyle.get(i));
                Matcher m_double = p_double.matcher(spannable);

                while (m_double.find()){

                    int start_double = m_double.start();
                    int end_double = m_double.end();

                    if (spannable.getSpans(start_double,end_double,UnderlineSpan.class).length==0){

                        UnderlineSpan underlineSpan = new UnderlineSpan();
                        spannable.setSpan(underlineSpan,start_double,end_double,Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);

                    }

                    if (spannable.getSpans(start_double,end_double,StyleSpan.class).length == 0){
                        StyleSpan span = new StyleSpan(Typeface.BOLD);
                        spannable.setSpan(span,start_double,end_double,Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);

                    }

                }

            } //for循环

            if (callback!=null){

                Global.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        callback.onCompleted(spannable);
                    }
                });
            }

        }
    }

    //设置字体加粗

    private void showStrong(final AsyncCallback callback) {

        Global.submit(new Runnable() {
            @Override
            public void run() {
                for (int i = 0;i<strongList.size();i++){

                    Pattern p = Pattern.compile(strongList.get(i));
                    Matcher m = p.matcher(spannable);

                    while (m.find()){

                        String strong =  m.group();
                        int start = m.start();
                        int end = m.end();
                        StyleSpan span = new StyleSpan(Typeface.BOLD);
                        spannable.setSpan(span,start,end,Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);

                    }
                }

                if (callback!=null){

                    Global.runOnUiThread(new Runnable() {
                        @Override
                        public void run() {

                          callback.onCompleted(spannable);
                        }
                    });
                }
            }
        });

    }

    //设置下划线

    private void showUnderline(final AsyncCallback callback) {

        Global.submit(new Runnable() {
            @Override
            public void run() {

                for (int i = 0;i<underlineList.size();i++){

                    Pattern p = Pattern.compile(underlineList.get(i));
                    Matcher m = p.matcher(spannable);

                    while (m.find()){

                        String underline =  m.group();
                        int start = m.start();
                        int end = m.end();
                        UnderlineSpan span = new UnderlineSpan();
                        spannable.setSpan(span,start,end,Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);

                    }
                }

                if (callback!=null){

                    Global.runOnUiThread(new Runnable() {
                        @Override
                        public void run() {

                            callback.onCompleted(spannable);
                        }
                    });

                }

            }
        });

    }


    //根据image标签异步下载图片并显示

    private void showPictures(){

                final Pattern p = Pattern.compile("<img.*?>");
                Matcher m = p.matcher(spannable);

                while(m.find()){

                    final String s = m.group();
                    final int start = m.start();
                    final int end = m.end();
                    Pattern p_src =  Pattern.compile("src\\s*=\\s*\"?(.*?)(\"|>|\\s+)");
                    Matcher m_src = p_src.matcher(s);
                    String path = "";
                    if (m_src.find()) {

                        String src =  m_src.group().split("=")[1];
                        path = src.substring(1,src.length()-1);

                    }

                    //利用spannableString和ImageSpan来替换掉这些图片
                    final int width = ScreenUtils.getScreenWidth();

                    //开启异步任务来下载图片。
            //        Log.e("aaaaaaaaaaaaaa","正在下载"+path);

                    final String url = path;

                            RoundedCorners roundedCorners= new RoundedCorners(1);
                            //通过RequestOptions扩展功能,override:采样率,因为ImageView就这么大,可以压缩图片,降低内存消耗
                            int offset = ((LinearLayout.LayoutParams)et_content.getLayoutParams()).rightMargin;
                            RequestOptions options=RequestOptions.bitmapTransform(roundedCorners).override(width-offset*2, width).centerCrop();
                            Glide.with(EditNoteActivity.this).load(url).apply(options).into(new SimpleTarget<Drawable>() {
                                @Override
                                public void onResourceReady(Drawable resource, Transition<? super Drawable> transition) {
                                    final Bitmap bitmap = ((BitmapDrawable)resource).getBitmap();
                                    if (bitmap!=null){

                                                Iterator<Integer> iterator = mDefaultSpans.keySet().iterator();
                                                while (iterator.hasNext()){  //去掉默认的图片

                                                    int index = iterator.next();
                                                    if (index == start){   //去掉当前位置的默认图片
                                                        spannable.removeSpan(mDefaultSpans.get(start));
                                                        break;
                                                    }
                                                }
                                                //替换成下载好的图片
                                                ImageSpan imageSpan = new ImageSpan(EditNoteActivity.this, bitmap);
                                                spannable.setSpan(imageSpan,start,end, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
                                                et_content.setText(spannable);
                                    }
                                }
                            });

                }
    }

    public interface OkHttpCallBack{

        public void onSuccess(Bitmap bitmap);

        public void onFailure(String reason);

    }


    private void handleStyleSpan(){


        String reg = "<span[^>]*>([^<]*)</span>";
        String reg1 = "<strong[^>]*>([^<]*)</strong>";

        Pattern p = Pattern.compile(reg);
        Matcher m = p.matcher(input);

        while (m.find()){

            int start3 = 0,start1 = 0,start2 = 0;
            int end1 = 0,end2 = 0,end3 = 0;

     //      Log.e("span", m.group());
           start1 = m.start();
           String spanStr = m.group();

           String startSpan = m.group().split(">")[0];
     //      Log.e("startSpan",startSpan);
           end1 = start1+startSpan.length()+1-1;
           start2 = end1+1;
           end2 = start2+m.group(1).length();
           start3 = end2+1;

           String endSpan = m.group().split("<")[2];
      //     Log.e("endSpan",endSpan);
           end3 = start3+endSpan.length()+1-1;

           if (spanStr.contains("underline")){

               underlineList.add(m.group(1));
     //          Log.e("underline",m.group(1));

           }
  //          Log.e("start1-end1",start1+"-"+end1);
 //           Log.e("start2-end2",start2+"-"+end2);
 //           Log.e("start3-end3",start3+"-"+end3);

        }
        Pattern p1 = Pattern.compile(reg1);
        Matcher m1 = p1.matcher(input);

        while (m1.find()){

    //        Log.e("strong",m1.group(1));
            strongList.add(m1.group(1));
        }

    }

    private void showDefaultContent(final AsyncCallback callback){
        //input是获取将被解析的字符串
        spannable = new SpannableString(input);  //input是经处理过格式标签的笔记内容
      //  et_content.setText(spannable);
    //    Log.e("input",input);

        Global.submit(new Runnable() {
            @Override
            public void run() {

                Pattern p = Pattern.compile("<img.*?>");
                Matcher m = p.matcher(input);

                while(m.find()){

    //                Log.e("YYPT_RGX", m.group());
                    final int start = m.start();
                    final int end = m.end();
                    final int width = ScreenUtils.getScreenWidth();

                    Bitmap  bitmap = ((BitmapDrawable) getResources().getDrawable(R.mipmap.nototool_image_loading)).getBitmap();
                    if (bitmap == null){

                        Log.e("bitmap","bitmap为null");

                    }else {

                        if (callback!=null){

                            ImageSpan imageSpan = new ImageSpan(EditNoteActivity.this, ImageUtils.zoomImage(bitmap,width,width));
                            spannable.setSpan(imageSpan,start,end, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
                            // et_content.setText(spannable);
                            mDefaultSpans.put(start,imageSpan);

                            Global.runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    callback.onCompleted(spannable);
                                }
                            });

                        }
                    }
                }

                Global.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {

                        callback.onFinish();
                    }
                });

            }
        });

    }

    private void initSystemID() {
        switch (ConstrantManager.NOTE_CURRENT_PAGE){

            case 0:
                mCurrentSysID = "";
                mCurrentSysName = "全部系统";
                break;
            case 1:
                mCurrentSysID = "630";
                mCurrentSysName = "课前预习系统";
                break;
            case 2:
                mCurrentSysID = "B10";
                mCurrentSysName = "课堂系统";
                break;
            case 3:
                mCurrentSysID = "510";
                mCurrentSysName = "课后作业系统";
                break;
            case 4:
                mCurrentSysID = "620";
                mCurrentSysName = "自由学习系统";
                break;
            case 5:
                mCurrentSysID = "S21";
                mCurrentSysName = "小管家系统";
                break;
            default:
                break;
        }

    }

    private void editNote(final boolean isNormal){

        NotePostBody postBody = new NotePostBody();
        postBody.setNoteContent(mNoteContent);
        Log.e("mNoteContent",mNoteContent);
        postBody.setNoteTitle(mNoteTitle);
        postBody.setOperateFlag(0);
        postBody.setUserID(ConstrantManager.childUserID);
        postBody.setUserName(ConstrantManager.childUserName);
        postBody.setNoteID(bean.getNoteID());
        postBody.setSubjectID(bean.getSubjectID());
        postBody.setSubjectName(bean.getSubjectName());
        postBody.setSystemID(bean.getSystemID());   //回传systemID
        postBody.setSystemName(bean.getSystemName());
        postBody.setResourceName(bean.getResourceName());
        postBody.setResourceID(bean.getResourceID());
        postBody.setIsKeyPoint(IsKeyPoint);
        postBody.setSchoolID(ConstrantManager.childSchoolID);

        if (NoteDetailbean!=null){

            postBody.setMaterialIndex(NoteDetailbean.getMaterialIndex());
            postBody.setMaterialID(NoteDetailbean.getMaterialID());

        }else {

            postBody.setMaterialIndex(bean.getMaterialIndex());
            postBody.setMaterialID(bean.getMaterialID());

        }

        SafeApiManager.getTestApi(3).addNote(postBody)
                .compose(NetworkTransformer.<OperateNoteResponse>commonSchedulers())
                .subscribe(new ResourceObserver<OperateNoteResponse>() {
                    @Override
                    public void onNext(OperateNoteResponse operateNoteResponse) {

                        if (operateNoteResponse.ErrorCode.substring(operateNoteResponse.ErrorCode.length()-2,operateNoteResponse.ErrorCode.length()).equals("00")){

                            isSummit = true;

                            if (isFromSearch){
                                NotifyFinishEvent finishEvent = new NotifyFinishEvent();
                                finishEvent.setFinishSigin(0);
                                EventBus.getDefault().post(finishEvent);
                            }

                            if (isNormal){

                                mHandler.postDelayed(new Runnable() {
                                    @Override
                                    public void run() {

                                        if (mLoadDialog!=null){

                                            mLoadDialog.dismiss();
                                        }
                                        NotifyToRefreshNoteEvent event = new NotifyToRefreshNoteEvent();
                                        event.setResult(1);
                                        EventBus.getDefault().post(event);

                                        TextViewUtils.showToast(EditNoteActivity.this,2,"保存成功！");
                                        finish();
                                    }
                                },1000);
                            }

                        }else {

                            TextViewUtils.showToast(EditNoteActivity.this,0,"保存失败，请重试！");

                        }

                    }

                    @Override
                    public void onError(Throwable e) {

                        TextViewUtils.showToast(EditNoteActivity.this,0,"接口访问失败，请检查网络环境后重试");

                        if (mLoadDialog!=null){

                            mLoadDialog.dismiss();
                        }

                    }

                    @Override
                    public void onComplete() {



                    }
                });

   /*     subscribe =  SafeApiManager.getTestApi(3).addNote(postBody)
                .compose(NetworkTransformer.<OperateNoteResponse>commonSchedulers())
                .subscribe(new Subscriber<OperateNoteResponse>() {
                    @Override
                    public void onCompleted() {

                        if (mLoadDialog!=null){

                            mLoadDialog.dismiss();
                        }
                    }

                    @Override
                    public void onError(Throwable e) {

                        TextViewUtils.showToast(EditNoteActivity.this,0,e.toString());

                        if (mLoadDialog!=null){

                            mLoadDialog.dismiss();
                        }

                    }

                    @Override
                    public void onNext(OperateNoteResponse deleteMessageResponse) {

                        if (deleteMessageResponse.ErrorCode.substring(deleteMessageResponse.ErrorCode.length()-2,deleteMessageResponse.ErrorCode.length()).equals("00")){

                            isSummit = true;

                            TextViewUtils.showToast(EditNoteActivity.this,2,"保存成功！");

                            if (isFromSearch){
                                NotifyFinishEvent finishEvent = new NotifyFinishEvent();
                                finishEvent.setFinishSigin(0);
                                EventBus.getDefault().post(finishEvent);
                            }

                            if (isNormal){

                                NotifyToRefreshNoteEvent event = new NotifyToRefreshNoteEvent();
                                event.setResult(1);
                                EventBus.getDefault().post(event);

                                mHandler.postDelayed(new Runnable() {
                                    @Override
                                    public void run() {
                                        finish();
                                    }
                                },0);
                            }

                        }else {

                            TextViewUtils.showToast(EditNoteActivity.this,0,deleteMessageResponse.Reason);

                        }

                    }
                });*/

    }


    public void getNoteByID(){

        NoteIDPostBody body = new NoteIDPostBody();
        body.setBackUpOne("");
        body.setBackUpTwo("");
        body.setNoteID(bean.getNoteID());
        body.setSecretKey("");
        body.setUserID(ConstrantManager.childUserID);
        body.setUserType(ConstrantManager.userType);

        SafeApiManager.getTestApi(3).getNoteByID(body)
                .compose(NetworkTransformer.<ApiResponse<NoteIDResponse>>commonSchedulers())
                .subscribe(new ResourceObserver<ApiResponse<NoteIDResponse>>() {
                    @Override
                    public void onNext(ApiResponse<NoteIDResponse> noteIDResponseApiResponse) {

                         NoteDetailbean = noteIDResponseApiResponse.Result.Notebean;

                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }


    public interface HttpCallBack {

        public void onSuccess(String result);

        public void onFailure(String error);

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {

        switch (requestCode) {

            case 0:  //相册
                if (resultCode == RESULT_OK) {

                    final Uri uri = data.getData();
                    String[] pojo = {MediaStore.Images.Media.DATA};
                    Cursor cursor = managedQuery(uri, pojo, null, null, null);
                    if (cursor != null) {

                        int colunm_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
                        cursor.moveToFirst();
                        String path = cursor.getString(colunm_index);
                        final File file = new File(path);
                        currentFile = file;

                        try {
                            String temp = DateUtils.dateToStamp(DateUtils.getNowDate());
                            FileManager.init(EditNoteActivity.this,ConstrantManager.FILE_MANAGER_ROOT);
                            imageEditedFile = FileManager.getFile(FileManager.getRootDir(),temp+".jpg");
                        } catch (ParseException e) {
                            e.printStackTrace();
                        }

                        IMGEditActivity.openEditor(EditNoteActivity.this,currentFile.getAbsolutePath(),imageEditedFile.getAbsolutePath());

                        //在这上传图片文件！！
                    }

                }
                break;

            case 1:  //拍照
                if (resultCode == RESULT_OK) {

                //    final File  file = new File(photoPath);
                //    currentFile = file;

                    sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE,Uri.fromFile(photo_file)));
                    currentFile = photo_file;

                    try {
                        String temp = DateUtils.dateToStamp(DateUtils.getNowDate());
                        FileManager.init(EditNoteActivity.this,ConstrantManager.FILE_MANAGER_ROOT);
                        imageEditedFile = FileManager.getFile(FileManager.getRootDir(),temp+".jpg");
                    } catch (ParseException e) {
                        e.printStackTrace();
                    }
                    IMGEditActivity.openEditor(EditNoteActivity.this,currentFile.getAbsolutePath(),imageEditedFile.getAbsolutePath());

                }
                break;

            case 2:

                //从文件读出编辑过的图片并展示

                if (resultCode == RESULT_OK){

                    if (imageEditedFile!=null && imageEditedFile.exists()){

                        TextViewUtils.showProgressDialog(EditNoteActivity.this,EditNoteActivity.class,"图片上传中...");
                        OkHttpUtils.getInstance().upImage(EditNoteActivity.this, imageEditedFile, new EditNoteActivity.HttpCallBack() {
                            @Override
                            public void onSuccess(String result) {
                                Gson gson = new Gson();

     //                           Log.e("result",result+"");
                                Response response = gson.fromJson(result, Response.class);

                                if (response.getResult()!=null&&response.getResult().size()>0){

                                    ImageUtil.showBitMap(EditNoteActivity.this,Uri.fromFile(imageEditedFile),response.getResult().get(0),et_content,screenWidth);
                                    TextViewUtils.hideProgressDialog(EditNoteActivity.this);
                                    TextViewUtils.showToast(EditNoteActivity.this,2,response.getReason());

                                }else {

                                    TextViewUtils.hideProgressDialog(EditNoteActivity.this);
                                    TextViewUtils.showToast(EditNoteActivity.this,0,response.getReason());
                                }
                            }

                            @Override
                            public void onFailure(String error) {

                                TextViewUtils.hideProgressDialog(EditNoteActivity.this);
                                TextViewUtils.showToast(EditNoteActivity.this,0,error);

                            }
                        });
                    }
                }
                break;
        }
    }

    private void initImageList() {

        mImageList.clear();
        mImageIndexs.clear();

        //input是获取将被解析的字符串
        String input = et_content.getText().toString();
        Pattern p = Pattern.compile("<img.*?>");
        Matcher m = p.matcher(input);

        while (m.find()) {

            String s = m.group();
            final int start = m.start();
            final int end = m.end();
            Pattern p_src = Pattern.compile("src\\s*=\\s*\"?(.*?)(\"|>|\\s+)");
            Matcher m_src = p_src.matcher(s);
            String path = "";
            if (m_src.find()) {

                String src = m_src.group().split("=")[1];
                path = src.substring(1, src.length() - 1);

            }

            //按图片在文中的顺序存储
            mImageList.add(path);
            mImageIndexs.add(start);

        }

  //      Log.e("ImageList",mImageList.size()+"hahah");
  //      Log.e("index",mImageIndexs.size()+"hahhah");
    }


    @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
    @Override
    public void onClick(View view) {
        int i = view.getId();
        if (i == R.id.iv_left_back) {//增加自动保存的逻辑

            if (isContentChange || isTitleChange || isKeyChange){  //标题或者内容发生改变的话提示要保存

                //弹出是否需要保存的提示框。
                TextViewUtils.showDialog(EditNoteActivity.this, "修改的内容未保存，您确定要退出吗？", new PositiveCallBack() {
                    @Override
                    public void positiveCallBack(AlertDialog dialog) {

                        if (!isSummit) {  //在没有发生提交操作的情况下执行保存操作


                            dialog.dismiss();
                            finish();

                            // editNote();  //自动保存
                        }

                    }
                }, new NegativeCallBack() {
                    @Override
                    public void negativeCallBack(AlertDialog dialog) {

                        dialog.dismiss();
                        //    finish();

                    }
                });
            }else {  //没有内容改变直接退出。

                finish();

            }

        } else if (i == R.id.tv_complete) {

            saveNote(true);

        } else if (i == R.id.ll_content) {
        } else if (i == R.id.tv_photo) {
            SoftInputUtil.hideSystemKeyBoard(EditNoteActivity.this, tv_save_note);
       //     showPopueWindow();

        } else if (i == R.id.ed_note_content) {

            SoftInputUtil.showSoftInput(EditNoteActivity.this,tv_save_note);
            initImageList();
            handleClick();

        } else if (i == R.id.iv_highlight_star) {

            isKeyChange = true;

            if (IsKeyPoint != 1) {  //标记为重点

                iv_highlight_star.setBackground(getResources().getDrawable(R.mipmap.notetool_highlight_star));
                IsKeyPoint = 1;
                TextViewUtils.showToast(EditNoteActivity.this, 2, "已标记为重点");

            } else { //取消重点标记

                iv_highlight_star.setBackground(getResources().getDrawable(R.mipmap.notetool_highlight_star_unselet));
                IsKeyPoint = 0;
                TextViewUtils.showToast(EditNoteActivity.this, 2, "已取消标记");

            }

        } else if (i == R.id.tv_choose_subject) {//选择学科
            iv_subject_right.setRotation(180);
            showPopClass();
            //    PopupWindowManager.showPopClass(AddNoteActivity.this,tv_choose_subject,subjectList,mFirstSubLocation,this);
            SoftInputUtil.hideSystemKeyBoard(EditNoteActivity.this, tv_save_note);

        } else if (i == R.id.tv_source) {//进行应用间的跳转

            Log.e("跳转链接", bean.getResourceAndroidLink() + "");

            //暂时屏蔽

         /*   if (NoteDetailbean!=null&&NoteDetailbean.getResourceAndroidLink() != null&&!NoteDetailbean.getResourceAndroidLink().equals("")) {

                lookSource(NoteDetailbean.getResourceAndroidLink());

            }*/

        } else if (i == R.id.ed_note_title){

            SoftInputUtil.showSoftInput(EditNoteActivity.this,tv_save_note);

        }
    }

    //跳转到相应的应用查看题目详情

    private void lookSource(String url) {

        try {
            String[] strings = url.split("%@%");               //截取url里面的内容
            for (int j = 0; j < strings.length; j++) {
                String string = strings[j];
            }
            String data = strings[strings.length-1];      //取最后一个的内容
            Intent intent = new Intent();
            intent.putExtra("Data", data);
            intent.putExtra("Flag", true);
            intent.putExtra("ShowDetails", true);
            intent.putExtra("StuId",ConstrantManager.childUserID);
            ComponentName componentName = new ComponentName(strings[0],       //取第一个和第二个作为参数
                    strings[1]);

            Log.e("data+",strings[strings.length-1]);
            Log.e("strings[0]+",strings[0]);
            Log.e("strings[1]+",strings[1]);

            intent.setComponent(componentName);

            if (DeviceUtils.isAppInstalled(EditNoteActivity.this, strings[0])) {  //传入包名并判断是否有安装关联的应用
                // startActivity(intent);
                startActivityForResult(intent, 0x01);
            } else {

                TextViewUtils.showToast(EditNoteActivity.this,1,"您未安装关联的应用");

            }
        } catch (Exception e) {

            TextViewUtils.showToast(EditNoteActivity.this,1,"链接无效，无法查看详情");

        }
    }

    private void saveNote(boolean isNormal) {

        SoftInputUtil.hideSystemKeyBoard(EditNoteActivity.this,tv_save_note);
        mNoteContent = et_content.getText().toString();
        mNoteTitle = et_titile.getText().toString();

        if (mNoteTitle.equals("")){

            mNoteTitle = DateUtils.getNowDate();
        }

        if (mNoteContent.equals("")){

            TextViewUtils.showToast(EditNoteActivity.this,1,"输入的内容不能为空！");

            if (mLoadDialog!=null){

                mLoadDialog.dismiss();
            }
            return;
        }

        String result = EditTextUtil.convertSpannedToRichText(et_content.getText());
        mNoteContent = result;

        mLoadDialog.show();
        editNote(isNormal);

   /*     if (NetworkUtil.hasNetwork(EditNoteActivity.this)){

            mLoadDialog.show();
            editNote(isNormal);
        }else {

            TextViewUtils.showToast(EditNoteActivity.this,1,"请连接网络重试！");
            mLoadDialog.dismiss();
        }*/

    }

    private void showPopClass(){
        View popView= LayoutInflater.from(EditNoteActivity.this).inflate(R.layout.pop_class_drop_list,null);
        if(popClass ==null){
            popClass = new PopupWindow(popView, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
            popClass.setFocusable(true);
            popClass.setOutsideTouchable(true);
            popClass.setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
            popClass.setOnDismissListener(new PopupWindow.OnDismissListener() {
                @Override
                public void onDismiss() {


                    isExpendClass=false;
                    iv_subject_right.setRotation(0);

                }
            });
        }
        popClass.showAsDropDown(tv_choose_subject,0, DeviceUtils.dip2px(EditNoteActivity.this,10));
        if(noteSubjectAdapter==null){
            listview = (ListView) popView.findViewById(R.id.listview);
            if(subjectList.size()<5){
                ViewGroup.LayoutParams layoutParams = listview.getLayoutParams();
                layoutParams.height= DeviceUtils.dip2px(EditNoteActivity.this,40)*subjectList.size();
                listview.setLayoutParams(layoutParams);
            }
            noteSubjectAdapter = new NoteSubjectAdapter(EditNoteActivity.this,subjectList);
            noteSubjectAdapter.setCurrentCheckIndex(mFirstSubLocation);
            listview.setAdapter(noteSubjectAdapter);
            popView.findViewById(R.id.view_mark).setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {

                    if(popClass!=null&&popClass.isShowing()){
                        popClass.dismiss();

                    }
                }
            });
            listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

                    isSubjectChange = true;

                    noteSubjectAdapter.setCurrentCheckIndex(position);
                    noteSubjectAdapter.notifyDataSetChanged();
                    popClass.dismiss();


                    tv_choose_subject.setText(subjectList.get(position).getSubjectName());
                    subjectName=subjectList.get(position).getSubjectName();
                    subjectId=subjectList.get(position).getSubjectID();

                    Log.e("SubjectName",subjectList.get(position).getSubjectName()+"");
                    Log.e("subjectId",subjectList.get(position).getSubjectID()+"");

                }
            });
        }else{
            noteSubjectAdapter.notifyDataSetChanged();
        }

    }

    private void getNoteSubjectList(){

        GetNoteSubjectPostBody body  = new GetNoteSubjectPostBody();

        body.setBackUpOne("");
        body.setBackUpTwo("");
        body.setSchoolID(ConstrantManager.childSchoolID);
        body.setToken(ConstrantManager.Token);
        body.setBackUpOne("");
        body.setUserID(ConstrantManager.childUserID);
        body.setUserType(ConstrantManager.userType);

        SafeApiManager.getTestApi(3).getNoteSubjectList(body)
                .compose(NetworkTransformer.<MySubjectResponse>commonSchedulers())
                .subscribe(new ResourceObserver<MySubjectResponse>() {
                    @Override
                    public void onNext(MySubjectResponse mySubjectResponse) {

                        if (mySubjectResponse.Result!=null&&mySubjectResponse.Result.size()>0){

                            subjectList.clear();

                            subjectList.addAll(mySubjectResponse.Result);


                            for (int i = 0;i<subjectList.size();i++){

                                if (bean.getSubjectID().equals(subjectList.get(i).getSubjectID())){

                                    mFirstSubLocation = i;
                                    break;
                                }

                            }
                        }else {

                            TextViewUtils.showToast(EditNoteActivity.this,0,mySubjectResponse.Reason);
                        }

                    }

                    @Override
                    public void onError(Throwable e) {

                        TextViewUtils.showToast(EditNoteActivity.this,0,e.toString());

                    }

                    @Override
                    public void onComplete() {

                    }
                });

    /*    SafeApiManager.getTestApi(3).getNoteSubjectList(body)
                .compose(NetworkTransformer.<MySubjectResponse>commonSchedulers())
                .subscribe(new Subscriber<MySubjectResponse>() {
                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable e) {

                        TextViewUtils.showToast(EditNoteActivity.this,0,e.toString());

                    }

                    @Override
                    public void onNext(MySubjectResponse mySubjectResponse) {

                        if (mySubjectResponse.Result!=null&&mySubjectResponse.Result.size()>0){

                            subjectList.clear();

                            subjectList.addAll(mySubjectResponse.Result);


                            for (int i = 0;i<subjectList.size();i++){

                                if (bean.getSubjectID().equals(subjectList.get(i).getSubjectID())){

                                    mFirstSubLocation = i;
                                    break;
                                }

                            }
                        }else {

                            TextViewUtils.showToast(EditNoteActivity.this,0,mySubjectResponse.Reason);
                        }
                    }
                });*/

    }

    private void handleClick() {


        boolean isOpened = false;

        final Spanned s = et_content.getText();
        final Editable editable = et_content.getEditableText();
        ImageSpan[] imagespans = s.getSpans(0, s.length(), ImageSpan.class);
        int selectStart = et_content.getSelectionStart();

        for (int i =0;i<imagespans.length;i++){

            if (isOpened){
                break;  //当图片已经打开，跳出最外层循环
            }

            final int start = s.getSpanStart(imagespans[i]);
            final int end = s.getSpanEnd(imagespans[i]);
            if (selectStart >= start && selectStart <= end){  //说明点击的是图片
                et_content.setSelection(end);  //将光标定位到图片的末尾，即下一行
                for (int j = 0;j<mImageIndexs.size();j++){

                    if (mImageIndexs.get(j) == start){

                        Log.e("点击第",j+"张图片");

                        LookPicture.look(mImageList,j, EditNoteActivity.this, new LookPicture.ImageDownLoadCallBack() {
                            @Override
                            public void onCompleted(String localPath) {

                                Iterator<Integer> iterator = mErrorSpans.keySet().iterator();
                                int fix = 0;
                                while (iterator.hasNext()){  //去掉默认的图片

                                    int index = iterator.next();
                                    if (index == start){

                                        fix = index;  //保存匹配到的位置
                                        //去掉当前位置的默认图片
                                        editable.removeSpan(mErrorSpans.get(start));
                                        //去读取下载好的图片文件
                                        int width = ScreenUtils.getScreenWidth();
                                        Bitmap bitmap = ImageUtil.getLocalSmallBitmap(localPath, width,700);
                                        ImageSpan imageSpan = new ImageSpan(EditNoteActivity.this, ImageUtils.zoomImage(bitmap,width,700));
                                        editable.setSpan(imageSpan,start,end, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
                                        et_content.setText(editable);

                                    }
                                }
                                mErrorSpans.remove(fix);

                            }

                            @Override
                            public void onError(String error) {

                                TextViewUtils.showToast(EditNoteActivity.this,0,"下载原图失败，请点击再试！");

                            }

                            @Override
                            public void onFileOpened(String localPath) {

                            }
                        });

                        SoftInputUtil.hideSystemKeyBoard(EditNoteActivity.this,tv_save_note);

                        isOpened = true;  //设置为图片是已打开状态

                        break;  //跳出最内层循环
                    }
                }
            }
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

     //   editNote(false);  //异常保存

        EventBus.getDefault().unregister(this);
        TextViewUtils.clearProgressDialog();
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {

        if (keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN) {
            long secondTime = System.currentTimeMillis();
            // long firstTime = 0;
            if (secondTime - firstTime > 2000) {

                if (isKeyChange||isTitleChange||isContentChange){

                    TextViewUtils.showDialog(EditNoteActivity.this, "修改的内容未保存，您确定要退出吗？", new PositiveCallBack() {
                        @Override
                        public void positiveCallBack(AlertDialog dialog) {

                     /*       if (mLoadDialog!=null){

                                mLoadDialog.setMsg("正在保存..");
                                mLoadDialog.show();
                            }

                            //创建笔记
                            saveNote(true);
                            dialog.dismiss();*/

                            dialog.dismiss();
                            finish();

                        }
                    }, new NegativeCallBack() {
                        @Override
                        public void negativeCallBack(AlertDialog dialog) {

                            dialog.dismiss();
                            //     finish();
                        }
                    });

                }else {
                    finish();
                }

                firstTime = secondTime;
                return true;

            } else{

            }
        }
        return super.onKeyDown(keyCode, event);
    }

}
